package com.test.flink_sinks;

import com.mysql.cj.jdbc.MysqlXADataSource;
import com.test.beans.LogBean;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.jdbc.*;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.util.function.SerializableSupplier;

import javax.sql.XADataSource;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;

/**
 * sink  不保证精确处理一次
 * exactlySink 保证精确处理一次
 */
public class E01JdbcSink02 {
    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port", 8888);
        StreamExecutionEnvironment webUI = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(configuration);
        // 设置全局并行度
        webUI.setParallelism(1);

        webUI.enableCheckpointing(2000) ;

        DataStreamSource<String> data = webUI.socketTextStream("127.0.0.1", 9001);
        // 数据转换成bean
        DataStream<LogBean> ds = data.map((MapFunction<String, LogBean>) line -> {
            // 数据在解析的时候可能会抛出异常 需要捕获异常防止程序停止  trycatch 快捷键 ctr+alt+t
            LogBean logBean = new LogBean();
            try {
                String[] arr = line.split(",");
                logBean.setName(String.valueOf(arr[0]));
                logBean.setLog(String.valueOf(arr[1]));
                logBean.setDesc(String.valueOf(arr[2]));
                logBean.setTimeStamp(Long.parseLong(arr[3]));
            } catch (Exception e) {

            }
            return logBean;
        });

        String sql = "insert into td_log (name, log, description, timestamp, create_time) values (?,?,?,?,?)";

        JdbcStatementBuilder<LogBean> statementBuilder = new JdbcStatementBuilder<LogBean>() {
            @Override
            public void accept(PreparedStatement preparedStatement, LogBean logBean) throws SQLException {
                preparedStatement.setString(1, logBean.getName());
                preparedStatement.setString(2, logBean.getLog());
                preparedStatement.setString(3, logBean.getDesc());
                preparedStatement.setLong(4, logBean.getTimeStamp());
                preparedStatement.setDate(5, new Date(Calendar.getInstance().getTime().getTime()));
            }
        };

        JdbcExecutionOptions executionOptions = JdbcExecutionOptions.builder()
                // 必须设置成 0
                // 连接服务器重试次数
                .withMaxRetries(0)
                // 批执行 不起作用
                .withBatchSize(2)
                // 间隔触发写入
                .withBatchIntervalMs(5000)
                .build();

        JdbcExactlyOnceOptions exactlyOnceOptions = JdbcExactlyOnceOptions.builder()
                // .withAllowOutOfOrderCommits(true)
                // 有些数据库支持  一个连接中多个事务   mysql只支持一个链接中一个事务
                //  mysql只支持一个链接中一个事务    mysql必须写true
                .withTransactionPerConnection(true)
                //  .withMaxCommitAttempts(10)  // 事务最大提交次数
                .build();

        SerializableSupplier<XADataSource> serializableSupplier = new SerializableSupplier<XADataSource>() {

            @Override
            public XADataSource get() {
                MysqlXADataSource xaDataSource = new MysqlXADataSource();
                xaDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/doe?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai");
                xaDataSource.setPassword("Sx123+654");
                xaDataSource.setUser("root");
                return xaDataSource;
            }
        };

        SinkFunction<LogBean> sink = JdbcSink.exactlyOnceSink(sql, statementBuilder, executionOptions, exactlyOnceOptions, serializableSupplier);

        ds.addSink(sink);

        webUI.execute();
    }
}
